/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from "vue";
import { getUserInfo, login, logout } from "@/api/user";
import { getroleinfo } from "@/api/depart";
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from "@/utils/accessToken";
import { resetRouter } from "@/router";
import { title, tokenName } from "@/config/settings";

const state = {
  accessToken: getAccessToken(),
  username: "",
  avatar: "",
  name: "",
  permissions: [],
  userpermi: [],
  type: "",
  role_id: "",
  instname: "",
};
const getters = {
  accessToken: (state) => state.accessToken,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  name: (state) => state.name,
  permissions: (state) => state.permissions,
  userpermi: (state) => state.userpermi,
  type: (state) => state.type,
  role_id: (state) => state.role_id,
  instname: (state) => state.instname,
};
const mutations = {
  setAccessToken(state, accessToken) {
    state.accessToken = accessToken;
    setAccessToken(accessToken);
  },
  setUsername(state, username) {
    state.username = username;
  },
  setInstname(state, instname) {
    state.instname = instname;
  },
  setName(state, name) {
    state.name = name;
  },
  setAvatar(state, avatar) {
    state.avatar = avatar;
  },
  setType(state, type) {
    state.type = type;
  },
  setRoleid(state, role_id) {
    state.role_id = role_id;
  },
  setPermissions(state, permissions) {
    state.permissions = permissions;
  },
  setUserpermi(state, userpermi) {
    state.userpermi = userpermi;
  },
};
const actions = {
  setPermissions({ commit }, permissions) {
    commit("setPermissions", permissions);
  },
  setUserpermi({ commit }, permissions) {
    commit("setUserpermi", permissions);
  },
  async login({ commit }, userInfo) {
    const { data, code, msg } = await login(userInfo);
    if(code == 400) {
      Vue.prototype.$baseMessage(
        msg,
        "error"
      );
    }
    const accessToken = data[tokenName];
    if (accessToken) {
      commit("setAccessToken", accessToken);
      const hour = new Date().getHours();
      const thisTime =
        hour < 8
          ? "早上好"
          : hour <= 11
          ? "上午好"
          : hour <= 13
          ? "中午好"
          : hour < 18
          ? "下午好"
          : "晚上好";
      Vue.prototype.$baseNotify(`欢迎登录${title}`, `${thisTime}！`);
    } else {
      Vue.prototype.$baseMessage(
        `登录接口异常，未正确返回${tokenName}...`,
        "error"
      );
    }
  },
  async getUserInfo({ commit, state }) {
    const { data } = await getUserInfo(state.accessToken);
    if (!data) {
      Vue.prototype.$baseMessage("验证失败，请重新登录...", "error");
      return false;
    }
    localStorage.setItem("userdata", JSON.stringify(data))
    data.username = data.mobile;
    data.permissions = ["admin"];
    let res = null;
    let { permissions, username, avatar, name, type, role_id, instname } = data;
    if (permissions && username && Array.isArray(permissions)) {
      commit("setPermissions", permissions);
      commit("setUsername", username);
      commit("setAvatar", avatar);
      commit("setName", name);
      commit("setType", type);
      commit("setRoleid", role_id);
      commit("setInstname", instname);
      try {
        if(role_id == 0) {
          res = null;
        } else {
          res = await getroleinfo({ id: role_id })
          // console.log(res)
        }

      } catch(error) {

      }
      commit("setUserpermi", res?.data?.permis && res.data?.permis.split(",").map(Number) || [])
      // return permissions
      return res?.data?.permis && res.data?.permis.split(",").map(Number) || [];
    } else {
      Vue.prototype.$baseMessage("用户信息接口异常", "error");
      return false;
    }
  },
  async logout({ dispatch }) {
    await logout(state.accessToken);
    await dispatch("resetAccessToken");
    await resetRouter();
  },
  resetAccessToken({ commit }) {
    commit("setPermissions", []);
    commit("setAccessToken", "");
    removeAccessToken();
  },
};
export default { state, getters, mutations, actions };
